package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.SubjectService;
import com.atguigu.servicebase.exceptionhandler.SelfExceptionHandler;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectListener extends AnalysisEventListener<SubjectData> {

    private SubjectService subjectService;
    public SubjectListener(){}
    public SubjectListener(SubjectService subjectService)
    {
        this.subjectService=subjectService;
    }

    /**
     * 一级分类是否存在  pid=0
     *
     * @param name  名称  先查询是否存在，若存在则不再添加
     * @return
     */
    public EduSubject existOneSubject(String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        wrapper.eq("title",name);
        //数据库查询
        EduSubject getOneSubject = subjectService.getOne(wrapper);
        return getOneSubject;
    }

    /**
     *
     * @param pid patent_id 就是对应一级分类的id
     * @param name  二级分类名称
     * @return
     */
    public EduSubject existTwoSubject(String pid,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",pid);
        wrapper.eq("title",name);
        //数据库查询
        EduSubject getTwoSubject = subjectService.getOne(wrapper);
        return getTwoSubject;
    }

    /***
     * 一行一行读取文件
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null)
        {
            throw new SelfExceptionHandler("文件为空",20002);
        }

        //第一分类为空，则添加
        String oneSubjectName = subjectData.getOneSubjectName();
        EduSubject existOneSubject =existOneSubject(oneSubjectName);
        if(existOneSubject==null)
        {
            existOneSubject=new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(oneSubjectName);
            //操作数据库添加
          subjectService.save(existOneSubject);


        }
        else{
            System.out.println("该第一分类已经存在");
        }

        //第二分类
        String pid=existOneSubject.getId();
        if(existTwoSubject(pid,subjectData.getTwoSubjectName())==null)
        {
            EduSubject twoSubject=new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            //保存进入数据库
            subjectService.save(twoSubject);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
